package com.erp.service.common;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.erp.service.entity.UploadResult;
import com.erp.service.util.JSONHelper;
import com.erp.service.util.net.HttpParams;
import com.erp.service.util.net.NDHttpRequest;
import com.erp.service.util.net.NDJSONRequest;
import com.erp.service.util.net.UploadProgressListener;
import com.erp.service.util.net.OnResponsedListener;
import com.erp.service.util.net.RequestMethod;

public class BizJSONRequest {

	private static final String TAG = "BizJSONRequest";

	private static NDJSONRequest request;
	private static Map<String, String> defaultHeader;
	private static String requestMethod;
	/**
	 * 妤犲矁鐦夋径杈Е閺冨爼妫块惄鎴濇儔
	 */
	private static OnAuthrizationFailListener onAuthrizationFailListener;

	public static void setAuthrizationFailListener(
			OnAuthrizationFailListener listener) {
		onAuthrizationFailListener = listener;
		request = intialNDJSONRequest();
	}

	/**
	 * 閸掓繂顬婇崠鏈抰tp婢剁繝淇婇幁锟�
	 */
	private static Map<String, String> initialHeader() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("OSTYPE", "android");// 缁崵绮烘穱鈩冧紖
		map.put("CompanyCode", "100");
		map.put("Nd-CompanyId", "100");
		return map;
	}

	/**
	 * 閸掓繂顬婇崠鏍嚞濮瑰倸顕挒鈽呯礉鐠佸墽鐤嗗鍌氱埗閻╂垵鎯�
	 * 
	 * @return
	 */
	protected static NDJSONRequest intialNDJSONRequest() {
		NDJSONRequest tempRequest = new NDJSONRequest(defaultHeader);
		tempRequest.setResponseListener(new OnResponsedListener() {
			@Override
			public HttpResponse onResponsed(HttpClient client,
					HttpUriRequest request, HttpResponse httpResponse) {
				int statusCode = httpResponse.getStatusLine().getStatusCode();
				String statusDescription = httpResponse.getStatusLine()
						.getReasonPhrase();
				if (statusCode == 405 || statusCode == 401)// 妤犲矁鐦夋径杈Е
				{
					if (onAuthrizationFailListener != null)
						return onAuthrizationFailListener.OnAuthrizationFail(
								client, request, httpResponse);
					else
						Log.d(TAG, "onAuthrizationFailListener 验证失败操作为null");
				}
				return httpResponse;
			}

		});

		return tempRequest;
	}

	/**
	 * 閺嶈宓侀悽銊﹀煕閻у妾版穱鈩冧紖鐠佸墽鐤唄ttp婢讹拷
	 */
	public static void setHeaderByUserInfo(String userid, String userGuid) {
		if (userid == null || userid == "")
			userid = "0";
		defaultHeader.put("USERGUID", userGuid);
		defaultHeader.put("userId", userid);
		request = intialNDJSONRequest();
	}

	/**
	 * 濞撳懐鈹栭悽銊﹀煕閻у妾版穱鈩冧紖婢讹拷
	 */
	public static void clearHeader() {
		request = intialNDJSONRequest();
	}

	/**
	 * 閸氭垶瀵氱�姝嶳L閸欐垿锟介惃鍕嚞濮瑰偊绱濇潻鏂挎礀閸樼喎顬婄�妤冾儊娑擄拷
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            閸欐垿锟界拠閿嬬湴閻ㄥ垊RL
	 * @param params
	 *            娴肩姴鍙嗛惃鍕棘閺佷即鏁崐鐓庮嚠閿涘苯鍞撮柈銊ょ窗鐏忓棔绱堕崗銉ф畱閸婅壈绻樼悰瀛秗lEncode
	 * @throws Exception
	 * 
	 * @return URL閹碉拷鍞悰銊ㄧ箼缁嬪绁┃鎰畱閸濆秴绨�
	 */
	public static String send(String url, HttpParams params) throws Exception {
		if (params == null)
			params = new HttpParams();
		return request
				.send(url, params.toNameValuePairs(), requestMethod, null)
				.toString();
	}

	/**
	 * 閸氭垶瀵氱�姝嶳L閸欐垿锟介惃鍕嚞濮瑰偊绱濇潻鏂挎礀閸樼喎顬婄�妤冾儊娑擄拷
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            閸欐垿锟界拠閿嬬湴閻ㄥ垊RL
	 * @param params
	 *            娴肩姴鍙嗛惃鍕棘閺佷即鏁崐鐓庮嚠閿涘苯鍞撮柈銊ょ窗鐏忓棔绱堕崗銉ф畱閸婅壈绻樼悰瀛秗lEncode
	 * @throws Exception
	 * 
	 * @return URL閹碉拷鍞悰銊ㄧ箼缁嬪绁┃鎰畱閸濆秴绨�
	 */
	public static String send(String url, HttpParams params, Object entity)
			throws Exception {
		if (params == null)
			params = new HttpParams();
		return request.send(url, params.toNameValuePairs(), RequestMethod.POST,
				request.getStringEntity(entity)).toString();
	}

	/**
	 * 閸氭垶瀵氱�姝嶳L閸欐垿锟介惃鍕嚞濮瑰偊绱濇潻鏂挎礀鐎圭偘缍�
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            閸欐垿锟界拠閿嬬湴閻ㄥ垊RL
	 * @param params
	 *            娴肩姴鍙嗛惃鍕棘閺佷即鏁崐鐓庮嚠閿涘苯鍞撮柈銊ょ窗鐏忓棔绱堕崗銉ф畱閸婅壈绻樼悰瀛秗lEncode
	 * @param RequestMethod
	 *            GET閹存湢OST
	 * @throws Exception
	 * 
	 * @return URL閹碉拷鍞悰銊ㄧ箼缁嬪绁┃鎰畱閸濆秴绨�
	 */
	public static <T> T sendForEntity(String url, HttpParams params,
			Class<T> returnType) throws Exception {
		if (params == null)
			params = new HttpParams();
		return request.sendForEntity(url, params.toNameValuePairs(), null,
				requestMethod, returnType);
	}

	/**
	 * 閸氭垶瀵氱�姝嶳L閸欐垿锟介惃鍕嚞濮瑰偊绱濇潻鏂挎礀鐎圭偘缍�
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            閸欐垿锟界拠閿嬬湴閻ㄥ垊RL
	 * @param params
	 *            娴肩姴鍙嗛惃鍕棘閺佷即鏁崐鐓庮嚠閿涘苯鍞撮柈銊ょ窗鐏忓棔绱堕崗銉ф畱閸婅壈绻樼悰瀛秗lEncode
	 * @param RequestMethod
	 *            GET閹存湢OST
	 * @throws Exception
	 * 
	 * @return URL閹碉拷鍞悰銊ㄧ箼缁嬪绁┃鎰畱閸濆秴绨�
	 */
	public static <T> T sendForEntity(String url, HttpParams params,
			Object entity, Class<T> returnType) throws Exception {
		if (params == null)
			params = new HttpParams();
		return request.sendForEntity(url, params.toNameValuePairs(), entity,
				RequestMethod.POST, returnType);
	}

	/**
	 * 閸氭垶瀵氱�姝嶳L閸欐垿锟介惃鍕嚞濮瑰偊绱濇潻鏂挎礀鐎圭偘缍嬮崚妤勩�
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            閸欐垿锟界拠閿嬬湴閻ㄥ垊RL
	 * @param params
	 *            娴肩姴鍙嗛惃鍕棘閺佷即鏁崐鐓庮嚠閿涘苯鍞撮柈銊ょ窗鐏忓棔绱堕崗銉ф畱閸婅壈绻樼悰瀛秗lEncode
	 * @param RequestMethod
	 *            GET閹存湢OST
	 * @throws Exception
	 * 
	 * @return URL閹碉拷鍞悰銊ㄧ箼缁嬪绁┃鎰畱閸濆秴绨�
	 */
	public static <T> List<T> sendForEntityList(String url, HttpParams params,
			Class<T> returnType) throws Exception {
		if (params == null)
			params = new HttpParams();
		return request.sendForEntityList(url, params.toNameValuePairs(), null,
				requestMethod, returnType);
	}

	/**
	 * 閸氭垶瀵氱�姝嶳L閸欐垿锟介惃鍕嚞濮瑰偊绱濇潻鏂挎礀鐎圭偘缍嬮崚妤勩�
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            閸欐垿锟界拠閿嬬湴閻ㄥ垊RL
	 * @param params
	 *            娴肩姴鍙嗛惃鍕棘閺佷即鏁崐鐓庮嚠閿涘苯鍞撮柈銊ょ窗鐏忓棔绱堕崗銉ф畱閸婅壈绻樼悰瀛秗lEncode
	 * @param RequestMethod
	 *            GET閹存湢OST
	 * @throws Exception
	 * 
	 * @return URL閹碉拷鍞悰銊ㄧ箼缁嬪绁┃鎰畱閸濆秴绨�
	 */
	public static <T> List<T> sendForEntityList(String url, HttpParams params,
			Object entity, Class<T> returnType) throws Exception {
		if (params == null)
			params = new HttpParams();
		return request.sendForEntityList(url, params.toNameValuePairs(),
				entity, RequestMethod.POST, returnType);
	}

	/**
	 * 閸氭垶瀵氱�姝嶳L閸欐垿锟介惃鍕嚞濮瑰偊绱濇潻鏂挎礀JSON鐎电钖�
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            閸欐垿锟界拠閿嬬湴閻ㄥ垊RL
	 * @param params
	 *            娴肩姴鍙嗛惃鍕棘閺佷即鏁崐鐓庮嚠閿涘苯鍞撮柈銊ょ窗鐏忓棔绱堕崗銉ф畱閸婅壈绻樼悰瀛秗lEncode
	 * @param RequestMethod
	 *            GET閹存湢OST
	 * @throws Exception
	 * 
	 * @return URL閹碉拷鍞悰銊ㄧ箼缁嬪绁┃鎰畱閸濆秴绨�
	 */
	public static JSONObject sendForJSONObject(String url, HttpParams params)
			throws Exception {
		if (params == null)
			params = new HttpParams();
		return request.sendForJSONObject(url, params.toNameValuePairs(), null,
				requestMethod);
	}

	/**
	 * 閸氭垶瀵氱�姝嶳L閸欐垿锟介惃鍕嚞濮瑰偊绱濇潻鏂挎礀JSON閺佹壆绮�
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            閸欐垿锟界拠閿嬬湴閻ㄥ垊RL
	 * @param params
	 *            娴肩姴鍙嗛惃鍕棘閺佷即鏁崐鐓庮嚠閿涘苯鍞撮柈銊ょ窗鐏忓棔绱堕崗銉ф畱閸婅壈绻樼悰瀛秗lEncode
	 * @param RequestMethod
	 *            GET閹存湢OST
	 * @throws Exception
	 * 
	 * @return URL閹碉拷鍞悰銊ㄧ箼缁嬪绁┃鎰畱閸濆秴绨�
	 */
	public static JSONArray sendForJSONArray(String url, HttpParams params)
			throws Exception {
		if (params == null)
			params = new HttpParams();
		return request.sendForJSONArray(url, params.toNameValuePairs(), null,
				requestMethod);
	}

	public static NDHttpRequest getCurrentHttpRequest() {
		return request;
	}

	/**
	 * @author ccl
	 * @param url
	 *            娑撳﹣绱堕崷鏉挎絻
	 * @param params
	 *            閸欏倹鏆�
	 * @param file
	 *            娑撳﹣绱堕弬鍥︽
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws AuthenticationException
	 */
	public static UploadResult upload(String url, HttpParams params, File file,
									  long startPosition, UploadProgressListener listener)
			throws ClientProtocolException, IOException,
			AuthenticationException {
		try {
			String uploadLengthString = request.upload(url,
					params.toNameValuePairs(), file, startPosition, listener)
					.toString();
			return JSONHelper.deserialize(UploadResult.class,
                    uploadLengthString);
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @author ccl
	 * @param url
	 *            娑撳﹣绱堕崷鏉挎絻
	 * @param params
	 *            閸欏倹鏆�
	 * @param file
	 *            娑撳﹣绱堕弬鍥︽
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws AuthenticationException
	 */
	public static UploadResult upload(String url, File file,
			UploadResult lastTimeResult, int tryTimes,
			UploadProgressListener listener) throws ClientProtocolException,
			IOException, AuthenticationException {
		HttpParams params = new HttpParams().add("fileName",
				file.getAbsolutePath());
		String serverFileName = null;
		long startPosition = 0;
		if (lastTimeResult != null) {
			startPosition = lastTimeResult.getUploadSize();
			serverFileName = lastTimeResult.getNewFilePath();
			params.add("newFilePath", serverFileName).add("startPosition",
					Long.toString(startPosition));
		}

		UploadResult result = upload(url, params, file, startPosition, listener);
		if (!result.isIsSuccess() && tryTimes > 1)
			return upload(url, file, result, tryTimes - 1, listener);
		return result;
	}

	static {
		defaultHeader = initialHeader();
		request = new NDJSONRequest(defaultHeader);
		requestMethod = RequestMethod.GET;
	}

	public static Map<String, String> getReqHeader() {
		return defaultHeader;
	}

}